#!/usr/bin/python
# -*- coding: UTF-8 -*-
#运行文件 人工智能.py
#作者 幽灵代码
#QQ 29672366
#邮箱 29672366@qq.com
#日期 2020.10.4

import sys
import os
import fnmatch
import xml
from xml.dom import minidom

rootpath = os.getcwd()+'/'
corename = 'core'
libname = 'lib'

import sqlite3 as db
import modelparse

#加载数据库
cx=db.connect(rootpath+"/db/data.db",check_same_thread = False)
cu=cx.cursor()

                
#创建数据库表
def create_table():
    try:
        create_tb_cmd='''
        CREATE TABLE IF NOT EXISTS register
        (modelname VARCHAR(40) PRIMARY KEY,
        vername VARCHAR(40),
        useable Boolean);
        '''
        cx.execute(create_tb_cmd)
        
        create_tb_cmd='''
        CREATE TABLE IF NOT EXISTS requestmap
        (question VARCHAR(40),
        classname VARCHAR(40),
        modulename VARCHAR(40),
        PRIMARY KEY (question,classname,modulename));
        '''
        cx.execute(create_tb_cmd)
        cx.commit()
    except:
        print(sqlite3_errmsg(db))
    return False

#模块检测
def loadAndCheck(modelname):
    #读取文件，生成python脚本,eval脚本
    #print("loadAndCheck:"+modelname)
    domtree = xml.dom.minidom.parse(rootpath+corename+'/'+modelname)
    if modelparse.modelToRegister(domtree):
        print(modelname+" 已注册")

#文件搜索函数
def iterFindFiles(path, fnexp): 
    for rootpath, dirs, files in os.walk(path): 
        for filename in fnmatch.filter(files, fnexp): 
            yield filename

#重置所有模块
def reset():
    create_table()
    sql = "update register set useable = 0"
    cu.execute(sql)
    cx.commit()
    #搜索核心模块 
    for filename in iterFindFiles(rootpath+corename, "*.xml"):
        loadAndCheck(filename)
        
#重新加载
def reload():
    sql = "delete from requestmap"
    cu.execute(sql)
    sql = "delete from register"
    cu.execute(sql)
    cx.commit()
    #搜索核心模块 
    for filename in iterFindFiles(rootpath+corename, "*.xml"):
        loadAndCheck(filename)

